package com.jack.helloworld.receiver;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.view.WindowManager;

import com.jack.helloworld.R;
import com.jack.helloworld.activity.LoginActivity;
import com.jack.helloworld.activity.mode.ActivityCollector;
import com.jack.helloworld.util.Constants;
import com.jack.helloworld.util.SystemUtil;
import com.jack.helloworld.util.ToastUtil;
import com.orhanobut.logger.Logger;

public class BaseReceiver extends BroadcastReceiver {
    public BaseReceiver() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        Logger.d("BaseReceiver#onReceive#action: " + action);
        if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
            if (SystemUtil.isNetworkAvailable(context)) {
                ToastUtil.showShortToast(context, R.string.network_available);
                if (SystemUtil.getNetState(context) == 1) {
                    ToastUtil.showShortToast(context, R.string.wifi_connected);
                }
            } else {
                ToastUtil.showShortToast(context, R.string.network_not_available);
            }
        }

        if (action.equals(Constants.MY_BROADCAST)) {
            ToastUtil.showShortToast(context, context.getString(R.string.receive_mybroadcast));
        }

        if (action.equals(Constants.LOCAL_BROADCAST)) {
            ToastUtil.showShortToast(context, context.getString(R.string.receive_localbroadcast));
        }

        if (action.equals(Constants.FORCE_OFFLINE_BROADCAST)) {
            showForceOfflineDialog(context);
        }

    }

    private void showForceOfflineDialog(final Context context) {
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
        dialogBuilder.setTitle("Warning");
        dialogBuilder.setMessage("You are forced to be offline. Please try to login again.");
        dialogBuilder.setCancelable(false);
        dialogBuilder.setPositiveButton("OK",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ActivityCollector.finishAll(); // 销毁所有活动
                        Intent intent = new Intent(context, LoginActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(intent); // 重新启动LoginActivity
                    }
                });
        AlertDialog alertDialog = dialogBuilder.create();
        // 需要设置AlertDialog的类型，保证在广播接收器中可以正常弹出
        alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST);
        alertDialog.show();
    }
}
